<template>
  <ContentWrap>
    <back :backOption="backOption" />
    <div>
      <el-card shadow="never">
        <template #header>
          <span>{{ infoOptions.data.name || '--' }}</span>
        </template>
        <el-descriptions :column="infoOptions.column">
          <div v-for="(item, index) in infoOptions.columns" :key="index">
            <el-descriptions-item :label="item.label">
              <div
                v-if="item.key == 'ip'"
                class="inline-flex"
                style="justify-content: space-between; width: 160px; align-items: center"
              >
                <span v-if="isShowIp" class="mr-10px">
                  {{ infoOptions.data.ip }}:{{ infoOptions.data.port }}
                </span>
                <span v-else class="mr-10px">**********</span>
                <el-Icon v-if="isShowIp"><Hide @click="isShowIp = false" /></el-Icon>
                <el-Icon v-else>
                  <View @click="isShowIp = true" />
                </el-Icon>
              </div>
              <span v-else-if="item.key == 'source'">
                {{
                  sourceMap.has(infoOptions.data.source)
                    ? sourceMap.get(infoOptions.data.source)
                    : '--'
                }}
              </span>
              <span v-else> {{ infoOptions.data[item.key] || '--' }}</span>
            </el-descriptions-item>
          </div>
        </el-descriptions>
      </el-card>
      <el-card class="mt-16px" shadow="never">
        <el-form label-width="100px" ref="formRef" :model="searchValue">
          <el-row>
            <el-col :span="6">
              <el-form-item label="操作人" prop="auditApplyPerson">
                <ns-input
                  v-model="searchValue.auditApplyPerson"
                  clearable
                  placeholder="请输入操作人"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="审核类型" prop="auditType">
                <el-select v-model="searchValue.auditType" clearable placeholder="请选择审核类型">
                  <el-option label="变更审核" value="变更审核" key="1" />
                  <el-option label="新增审核" value="新增审核" key="0" />
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="24" class="text-right">
              <el-button @click="searchReset" plain>重置</el-button>
              <el-button @click="search" plain>搜索</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-divider />
        <el-button type="primary" plain @click="merge">对比</el-button>
        <AsyncTable
          class="mt-12px"
          ref="tableRef"
          @selection-change="changeTable"
          :fetchData="fetchData"
          v-bind="tableOptions"
        />
      </el-card>
    </div>
  </ContentWrap>
</template>

<script setup lang="tsx">
import { sourceMap } from '@/utils/dict'
import { useRoute } from 'vue-router'
import { getDataSourceDetail } from '@/api/assetList/index'
import { levelHistoryPage } from '@/api/levelHistory'
import { Hide, View } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any
const route = useRoute()
const router = useRouter()
const assetId = ref<string>(route.query.id as string)
const backOption = ref({
  title: '返回'
})
const tableRef = ref()
const formRef = ref()
const isShowIp = ref(false)
const infoOptions = reactive({
  column: 5,
  columns: [
    { label: '资产IP:端口', key: 'ip' },
    { label: '资产类型', key: 'assetType' },
    { label: '数据源来源', key: 'source' },
    { label: '归属系统', key: 'sysName' },
    { label: '归属机构', key: 'deptName' }
  ],
  data: {}
})

const tableOptions = reactive({
  columns: [
    {
      type: 'selection'
    },
    { label: '操作时间', prop: 'createTime' },
    { label: '操作人', prop: 'auditApplyPerson' },
    // { label: '数据标准', prop: 'templateName' },
    { label: '操作内容', prop: 'auditType' },
    {
      label: '操作',
      render: ({ row }) => {
        return (
          <>
            <el-button link type="primary" onClick={() => goDetail(row)}>
              查看
            </el-button>
          </>
        )
      }
    }
  ],
  data: []
})

const searchValue = ref({
  auditApplyPerson: ''
})

// 搜索重置
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
// 搜索
const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
// 表格数据获取
const fetchData = async ({ page, pageSize }) => {
  const { data, count } = await levelHistoryPage({
    page,
    pageSize,
    dataSourceId: assetId.value,
    isOnlyDataSourceRoot: true,
    dataType: route.query.dataType,
    ...searchValue.value
  })
  return { data, count }
}

const ids = ref<string[]>([])
const chooseItems = ref<any[]>([])
const changeTable = (val) => {
  ids.value = []
  chooseItems.value = []
  val.map((item) => {
    ids.value.push(item.id)
    chooseItems.value.push(item)
  })
}

const openHistory = (row) => {
  // console.log(123)
  proxy?.$Drawer({
    params: {
      id: row.processInstanceId,
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `历史记录`,
    size: '60%',
    component: import('@/views/asset/pendingAsset/components/auditRecord.vue')
  })
}

const goDetail = (row) => {
  if (route.query.dataType == 'fileSource') {
    router.push({
      path: '/asset/fileAssetDetail',
      query: {
        id: row.dataSourceId,
        isPending: '1'
      }
    })
  } else if (route.query.dataType == 'dbSource') {
    router.push({
      path: '/asset/dataBaseDetail',
      query: {
        id: row.dataSourceId,
        isPending: '1'
      }
    })
  }
}

const merge = () => {
  console.log('chooseItems.value', chooseItems.value)
  let firstId = ''
  let nextId = ''
  if (chooseItems.value.length !== 2) {
    message.warning('只能选择两条数据进行比较')
    return
  } else {
    const data1 = chooseItems.value[0]
    const data2 = chooseItems.value[1]

    if (dayjs(data1.createTime).isBefore(dayjs(data2.createTime))) {
      firstId = data1.id
      nextId = data2.id
    } else {
      firstId = data2.id
      nextId = data1.id
    }
  }
  proxy?.$Drawer({
    params: {
      firstId: firstId, //更早的id
      nextId: nextId,
      isDatabase: 1,
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `历史记录对比`,
    size: '60%',
    component:
      route.query.dataType == 'fileSource'
        ? import('@/views/asset/pendingAsset/components/FileChange.vue')
        : import('@/views/asset/pendingAsset/components/databaseMerge.vue')
  })
}

const getData = async () => {
  const res = await getDataSourceDetail({ id: assetId.value })
  console.log('res', res)
  infoOptions.data = res.data
}

onMounted(async () => {
  getData()
})
</script>
